package com.x.share.mid.utils;

import java.io.InputStream;

import org.joda.time.DateTime;

import com.aliyun.oss.OSSClient;
import com.x.share.mid.prop.AliOSSProperties;

public class AliOSSUtils {

	/**
	 * 上传到阿里云(指定object key)
	 * @param ossProps
	 * @param inputStream
	 * @param name
	 */
	public static String uploadToOSS(AliOSSProperties ossProps, InputStream inputStream, String key){
		OSSClient ossClient = new OSSClient(ossProps.getGateway(), ossProps.getAppId(), ossProps.getAppKey());
		ossClient.putObject(ossProps.getBucket(), key, inputStream);
		return key;
	}
	
	/**
	 * 上传到阿里云oss
	 * @param ossProps
	 * @param inputStream
	 * @return
	 */
	public static String uploadToOSS(AliOSSProperties ossProps, InputStream inputStream) {
		String oid = generateOid();
		return uploadToOSS(ossProps, inputStream, oid);
	}
	
	public static String generateOid() {
		String oid = String.format("%s%s", DateTime.now().toString("yyyyMMddHHmmssS"),
				(int) ((1 + Math.random()) * 100));	
		return oid;
	}
	
	/**
	 * 从阿里云删除object
	 * @param ossProps
	 * @param oid
	 */
	public static void removeFromOSS(AliOSSProperties ossProps, String key) {
		OSSClient ossClient = new OSSClient(ossProps.getGateway(), ossProps.getAppId(), ossProps.getAppKey());
		ossClient.deleteObject(ossProps.getBucket(), key);
	}
}
